package cn.com.nes.common.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class ShakehandsUtil {
    public static final String url ="http://tools.wosoiot.com:8080/interfaces/v1/";
    public static final String amount ="admin@100580";
    public static final String key ="96e79218965eb72c92a549dd5a330112";


    public static JSONObject getCardInfo(String iccid){
//        String key= null;
        Map<String,String> paramMap=new HashMap<>();
//        try {
//            key = ShakehandsUtil.encoderByMd5("111111");
            paramMap.put("amount",amount);
            paramMap.put("key",key);
            paramMap.put("iccid",iccid);

//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        return getRequest(url+"card/info.action",paramMap);
    }
    /**
     * 获取数据
     * @param url
     * @param paramMap
     * @return
     */
    public static JSONObject getRequest(String url, Map<String,String> paramMap){
        JSONObject jsonObject=null;
        StringBuilder param=new StringBuilder();
        try {
            //处理参数
            int i=0;
            for(Map.Entry<String,String> entry:paramMap.entrySet()){
                if(i==0){
                    param.append("?");
                }else{
                    param.append("&");
                }
                param=param.append(entry.getKey()).append("=").append(entry.getValue());
                i++;
            }
            String wholeUrl=url+param;
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //创建登录请求的URL
            //        url=url.endsWith("/")?url:url+"/";
            //        url=StringUtils.isEmpty(companyId)?url:url+companyId;
            HttpGet httpget = new HttpGet(wholeUrl); // url
            // 设置请求头
            httpget=setHeader(httpget);
            HttpResponse response;

            response = httpclient.execute(httpget);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String str = EntityUtils.toString(response.getEntity(), "UTF-8"); // 请求成功后的返回值
                jsonObject=resultJson(str,jsonObject);
            }else{
                jsonObject=new JSONObject();
                jsonObject.put("status",0);
                jsonObject.put("msg","请求失败，请重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 设置请求头
     * @param httppost
     * @return
     */
    public static HttpPost setHeader(HttpPost httppost){
        httppost.setHeader("Accept","application/json, text/plain, */*");
        httppost.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
        httppost.setHeader("Accept-Encoding", "gzip, deflate");
        httppost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httppost.setHeader("Connection", "keep-alive");
        httppost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36");
        return httppost;
    }

    /**
     * 设置请求头
     * @param httpget
     * @return
     */
    public static HttpGet setHeader(HttpGet httpget){
        httpget.setHeader("Accept","application/json, text/plain, */*");
        httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
        httpget.setHeader("Accept-Encoding", "gzip, deflate");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36");
        return httpget;
    }

    /**
     * 获取json对象形式的数据
     * @param str
     * @param jsonObject
     * @return
     */
    public static JSONObject resultJson(String str,JSONObject jsonObject){
        jsonObject=new JSONObject();
        if(isJSONObject(str)){
            jsonObject = (JSONObject)JSONObject.parse(str.replaceAll("null", "\"\"").replaceAll("\"\"\"\"","\"\""));
        }else if(isJSONArray(str)){
            jsonObject.put("data",str);
        }else{
            jsonObject.put("success",false);
            jsonObject.put("msg","返回数据结构异常！");
        }
        return jsonObject;
    }

    /**
     * 简单判断返回数据是否为JSONObject
     * @param str
     * @return
     */
    private static boolean isJSONObject(String str) {
        return str.startsWith("{")?true:false;
    }

    /**
     * 简单判断返回数据是否为isJSONArray
     * @param str
     * @return
     */
    private static boolean isJSONArray(String str) {
        return str.startsWith("[")?true:false;
    }

    /**
     * MD5加密字符串
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String encoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((str).getBytes("UTF-8"));
        byte b[] = md5.digest();

        int i;
        StringBuffer buf = new StringBuffer("");

        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        return buf.toString();
    }

    public static void main(String[] args) {
        JSONObject json=ShakehandsUtil.getCardInfo("898604501220C0190337");
        System.out.println(json);
    }
}
